<%@page import="com.farm.parameter.FarmParameterService"%>
<%@page import="java.text.DecimalFormat"%>
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="/view/conf/farmtag.tld" prefix="PF"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!-- 批量上传附件 -->
<script src="text/lib/fileUpload/jquery.ui.widget.js"></script>
<script src="text/lib/fileUpload/jquery.iframe-transport.js"></script>
<script src="text/lib/fileUpload/jquery.fileupload.js"></script>
<link href="text/lib/fileUpload/jquery.fileupload.css" rel="stylesheet">
<style>
<!--
.bar {
	height: 18px;
	background: green;
}

.blocktip-title {
	cursor: auto;
	margin: 20px;
	padding: 30px;
	color: #888;
	border-color: #f4f4f4;
}

.file-block-box .stream-item {
	background-color: #ffffff;
}

.presessInfor {
	color: #428bca;
	margin: 4px;
}

.WfsUploadDropBox {
	border: 1px dashed #888;
	background-color: #f4f4f4;
}

.WfsUploadDropBox .WfsdropTip {
	text-align: center;
	color: #888;
	margin-top: 20px;
}

.WfsUploadDropBox.active {
	border: 1px solid #656464;
}

.WfsUploadDropBox.active .WfsdropTip {
	color: #656464;
}
-->
</style>
<!-- Modal -->
<div class="modal fade" id="uploadModalId" tabindex="-1" role="dialog"
	aria-labelledby="myModalLabel">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="myModalLabel">上传文件</h4>
			</div>
			<div class="modal-body" id="uploadModalContentId">
				<div class="WfsUploadDropBox">
					<div class="WfsdropTip">
						<i class="glyphicon glyphicon-paperclip"></i> 将文件<b>拖入此框</b>内(支持firfox,chrome)或通过点击<b>下方上传按钮</b>,进行文件上传
					</div>
					<div class="btn-group btn-group-justified" role="group"
						aria-label="Justified button group with nested dropdown"></div>
					<div id="fileQueue" style="text-align: left;">
						<div class="center-block text-center blocktip-title">
							<div style="text-align: left; font-size: 12px;">
								单个文件大小限制:<%
								DecimalFormat fnum = new DecimalFormat("##0.00 ");
								long size1 = FarmParameterService.getInstance().getParameterLong("config.doc.upload.length.max");
								float size1plus = ((float) size1) / (1025 * 1024);
							%>
								<b><%=fnum.format(size1plus)%>m</b>支持上传文件类型:<b> <PF:ParameterValue
										key="config.doc.upload.types" /></b>
							</div>
						</div>
					</div>
					<div class="row" id="fileListId" style="padding: 20px;">
						<!-- 文件列表 -->
					</div>
					<div
						style="text-align: center; padding-left: 20px; padding-right: 20px;">
						<div class="progress" id="uploadProgressId" style="display: none;">
							<div class="progress-bar  progress-bar-striped active"
								id="progressBarId" role="progressbar" aria-valuenow="60"
								aria-valuemin="0" aria-valuemax="100" style="width: 60%;">60%</div>
						</div>
						<div class="progress" id="serverStatId" style="display: none;">
							<div class="progress-bar progress-bar-success" role="progressbar"
								id="serverStatLableId" aria-valuenow="100" aria-valuemin="0"
								aria-valuemax="100" style="width: 100%"></div>
						</div>
					</div>
				</div>
			</div>
			<div class="modal-footer">
				<span class="btn btn-info fileinput-button"
					style="height: 34px; padding-top: 6px;" role="button"> <span
					style="font-size: 14px;">上传文件</span> <input id="fileupload"
					type="file" name="file" multiple>
				</span>
				<button type="button" onclick="submitUploadFile();"
					class="btn btn-primary">提交文件</button>
				<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">
	//单个文件大小
	var maxSize = parseInt('<PF:ParameterValue key="config.doc.upload.length.max"/>');
	var maxSizeTitle = (maxSize / 1024 / 1024).toFixed(2);
	var fileLimitType = '<PF:ParameterValue key="config.doc.upload.types"/>';
	var currentUserId = '${USEROBJ.id}';
	//单次上传文件数量
	var maxFileNum = 10;
	var allUploadFilesize = 0;
	//打开上传窗口
	function OpenUploadWin() {
		if (!currentUserId) {
			window.location = "login/PubLogin.html";
		}
		$('#uploadModalId').modal('show');
	}
	$(function() {
		$('body').bind('drop', function(ev) {
			ev.stopPropagation();
			ev.preventDefault();
		});

		$('#fileupload').fileupload({
			url : "upload/general.do",
			dataType : 'json',
			change : function(e, data) {
				return updateFileValidate(data.files);
			},
			done : function(e, data) {
				uploadComplete(data.result);
			},
			progressall : function(e, data) {
				runProgress(data.loaded, data.total);
			}
		});
	});
	//检查上传文件，返回值为是否允许上传
	function updateFileValidate(files) {
		//$('#fileListId').html(''); 
		if (files.length > maxFileNum) {
			alert("单次上传文件数量不能大于" + maxFileNum + "个!");
			return false;
		}
		var isOK = true;
		$(files).each(function(i, obj) {
			if (obj.size > maxSize) {
				alert("文件" + obj.name + "超大,请检查文件大小不能大于" + maxSizeTitle + "m");
				isOK = false;
			}
		});
		if (isOK) {
			allUploadFilesize = allUploadFilesize + files.length;
			$('#serverStatId').show();
		}
		return isOK;
	}

	//上传文件完成
	function uploadComplete(data) {
		var url = data.url;
		var state = data.STATE;
		var message = data.MESSAGE;
		var id = data.id;
		var fileName = data.fileName;
		if (state == 1) {
			allUploadFilesize--;
			showErrorMessage(message)
			allUploadFilesize = 0;
			$('#serverStatId').hide();
			return;
		}
		addFileNode(url, decodeURIComponent(fileName), id, "fileListId");
		allUploadFilesize--;
		if (allUploadFilesize <= 0) {
			allUploadFilesize = 0;
			$('#serverStatId').hide();
		}
	}
	//加载进度条
	function runProgress(cProgess, totalProgess) {
		var progress = parseInt(cProgess / totalProgess * 100, 10);
		loadProgress(progress);
		if (progress == 100) {
			$('#serverStatId').show();
			loadRemoteProcess(true);
		} else {
			$('#serverStatId').hide();
		}

	}

	var isLoadRemotProecess = false;
	//检查远程进度
	function loadRemoteProcess(state) {
		isLoadRemotProecess = state;
		if (state) {
			setTimeout("doloadRemoteProcess()", 1000); //延迟1秒
		}
	}
	//加载远程进度
	function doloadRemoteProcess() {
		$.post("upload/PubUploadProcess.do", {}, function(flag) {
			if (flag.STATE == 0) {
				$('#serverStatLableId')
						.text('等待服务器处理中' + flag.process + '%...');
				if (flag.process > 99) {
					isLoadRemotProecess = false;
				}
				if (isLoadRemotProecess) {
					setTimeout("doloadRemoteProcess()", 1000); //延迟1秒	
				}
			} else {
				alert(flag.MESSAGE);
			}
		}, 'json');
	}
	function loadProgress(progress) {
		if (progress > 0 && progress < 99) {
			$('#uploadProgressId').show();
			$('#progressBarId').attr('aria-valuenow', progress);
			$('#progressBarId').text(progress + '%');
			$('#progressBarId').attr('style', "width: " + progress + "%;");
		} else {
			$('#uploadProgressId').hide();
		}
	}
	//添加一个界面文件元素
	function addFileNode(imgUrl, fileName, fileId, domBoxId) {
		$('.blocktip-title').hide();
		var html = '<div class="col-sm-12 file-block-box"   id="file_'+fileId+'">';
		html = html + '		<div class="stream-item" >';
		html = html + '				<div class="media">';
		html = html + '					<div class="pull-left">';
		html = html + '						<img  alt="'+fileName+'" src="'+imgUrl+'">';
		html = html + '					</div>';
		html = html + '					<div class="media-body" >';
		html = html
				+ '<i onclick="removeFile(\''
				+ fileId
				+ '\');" title="删除临时文件" class="glyphicon glyphicon-remove pull-right" ></i>';
		html = html + '						<div class="file-title" >' + fileName + '</div>';
		html = html + '					</div>';
		html = html + '				</div>';
		html = html + '		</div>';
		html = html
				+ '<input type="hidden" name="fileId" value="'+fileId+'" /></div>';
		$('#' + domBoxId).append(html);
	}
	//删除一个文件
	function removeFile(fileId) {
		$.post('upload/logicDel.do', {
			id : fileId
		}, function(data) {
			if (data.STATE == 0) {
				hideFileBox(fileId);
			} else {
				showErrorMessage(data.MESSAGE);
			}
		}, 'json');
	}
	//刪除一個附件圖標元素
	function hideFileBox(fileid) {
		$("#file_" + fileid).remove();
		//判断附件是否上传
		if ($("input[name='fileId']").length == 0) {
			$('.blocktip-title').show();
		}
	}
	//顯示错误消息弹框
	function showErrorMessage(message) {
		alert(message);
	}
	//提交上传的文件
	function submitUploadFile() {
		$('#serverStatId').show();
		$('#serverStatLableId').text('等待服务器处理中...');
		var fileids = "";
		$('#fileListId input').each(function(i, obj) {
			fileids = fileids + "," + $(obj).val();
		});
		submitFile(fileids);
	}
	//提交一个文件为持久状态
	function submitFile(fileIds) {
		$.post('wfile/add.do', {
			wdapfileids : fileIds,
			dirid : '${cdir.id}'
		}, function(data) {
			if (data.STATE != 0) {
				showErrorMessage(data.MESSAGE);
			}
			window.location.reload();
			$('#serverStatId').hide();
		}, 'json');
	}
</script>
<script>
	$(function() {
		var uploadDrop = document.getElementById('uploadModalContentId');
		uploadDrop.addEventListener('dragover', function(event) {
			$('.WfsUploadDropBox').addClass("active");
			event.preventDefault();
		});
		uploadDrop.addEventListener('dragenter', function(event) {
			event.preventDefault();
		});
		uploadDrop.addEventListener('dragleave', function(event) {
			$('.WfsUploadDropBox').removeClass("active");
			event.preventDefault();
		});
		uploadDrop.addEventListener('drop', function(event) {
			$('.WfsUploadDropBox').removeClass("active");
			event.preventDefault();
			var fileList = Array.from(event.dataTransfer.files);
			var uploadAble = updateFileValidate(fileList);
			if (uploadAble) {
				for (var i = 0; i < fileList.length; i++) {
					sendFileByXHR('upload/general.do', fileList[i]);
				}
			}
		});
	});
	function sendFileByXHR(url, fielObj) {
		// body...
		var xhr = new XMLHttpRequest();
		xhr.upload.onprogress = function(event) {
			runProgress(event.loaded, event.total);
		}
		xhr.onreadystatechange = function() {
			if (xhr.status === 200 && xhr.readyState === 4) {
				var jsonObject = JSON.parse(xhr.responseText, null);
				uploadComplete(jsonObject);
			}
		}
		xhr.onabort = function(event) {
			//终止
			console.log('abort');
		}
		xhr.onerror = function(event) {
			console.log('error');
			showErrorMessage('xhr.onerror-error');
		}
		var data = new FormData();
		data.append("file", fielObj);
		xhr.open('POST', url, true);
		xhr.send(data);
	}
</script>